package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.query.TravelCommendQueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
@RequestMapping("travelCommend")
public class TravelCommendController {
    @Autowired
    private ITravelCommendService travelCommendService;

    @Autowired
    ServletContext servletContext;

    /**
     * 游记推荐页面分页/高级查询
     *
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo") TravelCommendQueryObject qo) {
        //按照推荐时间倒序排列
        qo.setOrderBy("tc.schedule desc");
        model.addAttribute("result", travelCommendService.queryForList(qo));
        return "travel/commend";
    }

    /**
     * 游记推荐新增/编辑
     *
     * @param travelCommend
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(MultipartFile file, TravelCommend travelCommend) {
        JSONResult result = new JSONResult();
        try {
            if (file != null && file.getSize() > 0) {
                String imgUrl = UploadUtil.upload(file, servletContext.getRealPath("/upload"));
                travelCommend.setCoverUrl(imgUrl);
            }
            if (travelCommend.getId() != null) {
                travelCommendService.update(travelCommend);
            } else {
                travelCommendService.save(travelCommend);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
